package com.ncmmall.mall.controller.business.distribution;

import com.ncmmall.application.business.distribution.DistributorWithdrawRecordApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.lang.Requires;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.distribution.DistributorWithdrawRecord;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 分销提现管理
 */
@Controller
@RequestMapping("/mall/distribution/withdraw")
@Slf4j
public class DistributorWithdrawRecordController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private DistributorWithdrawRecordApplication distributorWithdrawRecordApplication;

    /**
     * 分销商申请提现列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, @RequestParam(defaultValue = "1") int pageNo,
                       @RequestParam(defaultValue = "10") int pageSize, DistributorWithdrawRecord params) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageNo).setPageSize(pageSize);
        Map<String, Object> map = new HashMap<>();
        String hql = buildHQL("select r from DistributorWithdrawRecord r where 1 = 1", params, map);

        QueryPage<DistributorWithdrawRecord> page = queryChannelService.findPage(hql, pageRequest.setParams(map), DistributorWithdrawRecord.class);
        model.addAttribute("page", page);
        model.addAttribute("params", params);

        return "mall/distribution/withdraw/list";
    }

    private String buildHQL(String hql, DistributorWithdrawRecord params, Map<String, Object> map) {

//        WebUser user = params.getDistributor().getUser();
//        if (user != null) {
//            if (StringUtils.isNotBlank(user.getMobile())) {
//                hql += " and d.member.mobile like :mobile";
//                map.put("mobile", "%" + user.getMobile() + "%");
//            }
//
//            if (StringUtils.isNotBlank(user.getRealName())) {
//                hql += " and d.member.realName like :realName";
//                map.put("realName", "%" + user.getRealName() + "%");
//            }
//        }

        if (params.getDistributor() != null && params.getDistributor().getUser() != null && StringUtils.isNotBlank(params.getDistributor().getUser().getMobile())) {
            hql += " and r.distributor.user.mobile like :mobile";
            map.put("mobile", "%" + params.getDistributor().getUser().getMobile() + "%");
        }

        if (params.getPayType() > 0) {
            hql += " and r.payType = :payType";
            map.put("payType", params.getPayType());
        }

        if (params.getStatus() > 0) {
            hql += " and r.status = :status";
            map.put("status", params.getStatus());
        }

        return hql + " order by r.createTime desc";
    }


    /**
     * 审核微信提现
     *
     * @param ids    提现单号
     * @param status 审核状态 3、拒绝  4、支付
     * @param note   拒绝支付备注
     */
    @RequestMapping(value = "/checkWechatWithdraw", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> checkWechatWithdraw(HttpServletRequest request, String ids, Integer status, String note) {
        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalRequestException("request must be ajax !");
            }

            Requires.hasLength(ids, "请选择提现记录");
            Requires.isTrue(status != null && (status == 3 || status == 4), "审核状态不正确");
            if (status == 3) {
                Requires.hasLength(note, "请填写备注");
            }


            DistributorWithdrawRecord record = queryChannelService.findOne(DistributorWithdrawRecord.class, ids);
            distributorWithdrawRecordApplication.checkWechatWithdraw(record, status, note, Securitys.currentUser());

            return ImmutableMap.of("status", true);
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[审核分销商提现异常]", e);
            return ImmutableMap.of("status", false, "message", "审核异常");
        }
    }

    /**
     * 审核银行卡提现
     */
    @RequestMapping(value = "/checkBankCardWithdraw", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> checkBankCardWithdraw(HttpServletRequest request, String ids, Integer status, String note, String image) {
        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            Requires.hasLength(ids, "请选择提现记录");
            Requires.isTrue(status != null && (status == 3 || status == 4), "审核状态不正确");
            if (status == 3) {
                Requires.hasLength(note, "请填写备注");
            } else {
                Requires.hasLength(image, "请上传转账凭证");
            }

            DistributorWithdrawRecord record = queryChannelService.findOne(DistributorWithdrawRecord.class, ids);
            distributorWithdrawRecordApplication.checkBankCardWithdraw(record, status, note, image, Securitys.currentUser());
            return ImmutableMap.of("status", true, "message", "审核成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("审核分销商提现异常", e);
            return ImmutableMap.of("status", false, "message", "审核异常");
        }
    }


    /**
     * 审核银行卡提现
     */
    @RequestMapping(value = "/checkBankCardWithdraw", method = RequestMethod.GET)
    public String checkBankCardWithdraw(String ids, Model model) {
        model.addAttribute("ids", ids);
        return "mall/distribution/withdraw/check";
    }

}
